package com.universityJob.modules.app.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.universityJob.common.exception.RRException;
import com.universityJob.common.utils.R;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;

/**
 * @author mao on 2021/5/17.
 * @version 1.0 maozhijob@163.com
 */
@Component
public class WXPublicUtils {
    @Value("${renren.jwt.secret}")
    private  String wxtoken ;
    @Value("${app.appid}")
    private String appid;
    @Value("${app.appsecret}")
    private String appsecret;
    /**
     * 验证Token
     * @param msgSignature 签名串，对应URL参数的signature
     * @param timeStamp 时间戳，对应URL参数的timestamp
     * @param nonce 随机串，对应URL参数的nonce
     *
     * @return 是否为安全签名
     * @throws RRException 执行失败，请查看该异常的错误码和具体的错误信息
     */
    public boolean verifyUrl(String msgSignature, String timeStamp, String nonce)
            throws RRException {
        // 这里的 WXPublicConstants.TOKEN 填写你自己设置的Token就可以了
        String signature = SHA1.getSHA1(wxtoken, timeStamp, nonce);
        if (!signature.equals(msgSignature)) {
            throw new RRException("验证出错");
        }
        return true;
    }
    public String getOpenId(String userId){
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        url += "?appid="+appid;//自己的appid
        url += "&secret="+appsecret;//密匙
        url += "&js_code=" + userId;
        url += "&grant_type=authorization_code";
        byte[] res = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
            res = IOUtils.toByteArray(response.getEntity().getContent());
        } catch (Exception e) {
            return "";
        } finally {
            if (httpget != null) {
                httpget.abort();
            }
            httpclient.getConnectionManager().shutdown();
        }
        JSONObject jo = null;
        try {
            jo = JSON.parseObject(new String(res, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String openid = jo.getString("openid");

        return openid;
    }
}
